package cn.fastoo.common.logger;

import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Level;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lowkey on 17/8/16.
 */

public class DingdingAppender extends WriterAppender {


    private final static String EXCEPTION_DINGDING_CHANNEL = "";

    @Override
    public void append(LoggingEvent event) {
        if(Level.ERROR_INT != event.getLevel().toInt()){
            return;
        }
        final JSONObject content = new JSONObject();
        final JSONObject markdown = new JSONObject();
        markdown.put("text",getLayout().format(event));
        markdown.put("title","异常信息");
        content.put("msgtype","markdown");
        content.put("markdown",markdown);

        /*
        try {
            readContentFromPostJson(EXCEPTION_DINGDING_CHANNEL,content.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }




    /**
     * post请求，post域为json格式
     *
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    public static String readContentFromPostJson(String url, String content) throws IOException {
        URL postUrl = new URL(url);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.addRequestProperty("Accept-Charset", "UTF-8");
        connection.setConnectTimeout(1000);
        connection.setReadTimeout(3000);
        PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
        out.println(content);
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        // 关闭连接
        connection.disconnect();
        return sb.toString();
    }

}
